package cn.tworice.admin.service.impl;

import cn.tworice.admin.service.WechatExplosiveTextService;

import java.io.IOException;
import java.util.*;

import cn.tworice.admin.utils.ConstantUtil;
import cn.tworice.admin.utils.HttpUtils;
import cn.tworice.admin.utils.UploadWechatFiles;
import cn.tworice.admin.vo.Message;
import cn.tworice.admin.vo.RequestMessage;
import cn.tworice.admin.vo.Token;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import org.springframework.stereotype.Service;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class WechatExplosiveTextServiceImpl implements WechatExplosiveTextService {

    // 定义API URL和相关信息
    private static final String NEWS_API_URL = "https://s.weibo.com/top/summary/summary?cate=realtimehot"; // 替换为实际的新闻API URL
    private static final String YWNEWS_API_URL = "https://s.weibo.com/top/summary/summary?cate=socialevent"; // 替换为实际的新闻API URL
    private static final String Cookie = "PC_TOKEN=284221658f; SUB=_2A25LW1CgDeRhGeNJ61UR9CnLyD6IHXVoGexorDV8PUNbmtANLRWtkW9NSBVBbZuLZsdPI4fl_qHTGDBVmv4MDPx-; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFKB6WAC.z8C1rnLK._W_Sl5NHD95QfS05NehBNS0eEWs4DqcjS-JLoqPi.dXX_BcyLdntt; ALF=02_1720102384; _s_tentry=-; Apache=7987230380960.544.1717510408039; SINAGLOBAL=7987230380960.544.1717510408039; ULV=1717510408041:1:1:1:7987230380960.544.1717510408039:"; // 替换为实际的新闻TOKEN
    private static final String NEWS_API_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"; // 替换为实际的新闻USER_AGENT
    private static final String CHATGPT_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k"; // 替换为实际的ChatGPT API URL
    private static final String WECHAT_ACCESS_TOKEN = "your_access_token"; // 替换为您的微信公众号访问令牌
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    public static final String API_KEY = "8KAFO4FzTk7Jv9NUbSZpnBlF";
    public static final String SECRET_KEY = "x7IDKddirE8Lp1ZX11bsiD87vWwkqtvU";
    //请求参数
    private RequestMessage requestBody = new RequestMessage();
    private List<Message> messages = new ArrayList<>();
    //响应超时时间
    private int responseTimeOut = 5000;

    @Override
    @Transactional
    public boolean NewsAutomation() throws Exception {
        // 1. 搜集热点新闻
        List<String> mergedList = new ArrayList();
//        List<String> hotNews = fetchHotNews(NEWS_API_URL);
        List<String> hotNews_yw = fetchHotNews(NEWS_API_URL);
        if (hotNews_yw.size() == 0) {
            System.out.println("没有获取到热搜");
            return false;
        }
//        mergedList.addAll(hotNews);
        mergedList.addAll(hotNews_yw);
        // 2. 循环调用ChatGPT API生成爆文
        //获取wenxin -accesstoken
        String generatedArticle = "";
        int i = mergedList.size();
        for (int j = 0; j < i; j++) {
            List<String> generatedArticleList = new ArrayList();
            generatedArticle = generateArticleWithChatGPT(mergedList.get(j).toString());
            generatedArticleList.add(generatedArticle);
            // 4. 发布文章到微信公众号
            boolean isPublished = publishArticleToWeChat(generatedArticleList, WECHAT_ACCESS_TOKEN);

            if (isPublished) {
                System.out.println("文章发布成功！");
            } else {
                System.out.println("文章发布失败！");
            }
        }


        return false;
    }

    // 1. 搜集热点新闻的函数
    public static List<String> fetchHotNews(String apiUrl) throws IOException, JSONException {
        // 实现新闻API的调用和数据解析
        // 返回热点新闻标题列表
        // 根据新闻标题构建请求体
        // 创建URL对象
        List hotNews = new ArrayList();
        // 微博热搜URL
        String weiboHotSearchUrl = apiUrl;

        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpGet实例
        HttpGet httpGet = new HttpGet(weiboHotSearchUrl);
        // 添加请求头
        httpGet.setHeader("Cookie", Cookie);
        httpGet.setHeader("User-Agent", NEWS_API_USER_AGENT);

        try {
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 读取HTML内容
            String html = entity != null ? EntityUtils.toString(entity, "UTF-8") : null;

            // 使用Jsoup解析HTML
            Document doc = Jsoup.parse(html);
            // 根据微博热搜页面结构选择元素，这里需要根据实际情况调整选择器
            Elements hotSearchItems = doc.select("td.td-02");

            // 遍历热搜榜单并打印
            for (int i = 1; i < hotSearchItems.size(); i++) {
                Element item = hotSearchItems.get(i);
                String hotSearchText = item.child(0).text();
                //String hotSearchText = item.child(1).text();浏览量
                if (i < 3) {
                    hotNews.add(hotSearchText);
                    System.out.println(hotSearchText);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return hotNews;
    }

    // 2. 调用文心一言 API生成爆文的函数
    public String generateArticleWithChatGPT(String hotNew) throws IOException, JSONException {
        // 构建请求体
        String Content = buildWxYyContent(hotNew);
        String s = sendPostRequest(getAccessToken(), Content);
        Map maps = (Map) JSON.parse(s);
        String result = (String) maps.get("result");
        System.out.println(result);
        Message message = new Message("assistant", result);
        messages.add(message);
        return result;
    }


    // 3. 发布文章到微信公众号的函数
    public static boolean publishArticleToWeChat(List<String> articles, String accessToken) throws Exception {
        boolean isornot = false;
        //1.获取token
        Token token = getToken(ConstantUtil.app_id, ConstantUtil.app_secret);
        for (String article : articles) {
            //2.上传图片素材
            String imeMediaId = UploadWechatFiles.uploadimg(token);
            log.info("图片上传成功，返回值为：" + imeMediaId);
            Map maps = (Map) JSON.parse(imeMediaId);
            String media_id = (String) maps.get("media_id");
            //将文章按照正则进行区分
            String[] strings = UploadWechatFiles.splitTitleAndContent(article);
            //3.发布文章到微信
            String draftMeteid = UploadWechatFiles.addDraft(strings[0], "陈旺鑫", strings[1], token, media_id);
            log.info("草稿上传成功，返回值为：" + draftMeteid.toString());
            UploadWechatFiles.publishWx(draftMeteid, token);
            isornot = true;
        }
        return isornot;
    }

    //获取文心一言accesstoken

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        // 使用fastjson的JSONObject来解析JSON字符串
        JSONObject jsonResponse = JSON.parseObject(response.body().string());

        // 从JSONObject中获取access_token字符串
        String accessToken = jsonResponse.getString("access_token");
        return accessToken;
    }

    // 辅助函数：构建ChatGPT请求体
    public String buildWxYyContent(String hotNew) throws IOException, JSONException {
        Message message = new Message("user", "您是一名有10年撰写公众号文章经验的运营者，您熟悉掌握爆款文章的结构和写法，请您根据" + hotNew + "这个标题，并参照金字塔原理大纲写一篇800字左右的小文章，从认知心理学角度，要求举例说明" + hotNew + "常见冲突的问题，另外增加一些金句对文章进行润色,并在每段生成后换行再输出");
        messages.add(message);
        requestBody.setMessages(messages);
        requestBody.setUser_id("cwx");
        String jsonStr = JSON.toJSONString(requestBody);
        return jsonStr;
    }

    // 辅助函数：解析ChatGPT响应
    public static String parseChatGPTResponse(String response) throws IOException {
        // 解析API响应并提取生成的文章
        return "";
    }

    /**
     * 发送prompt
     *
     * @param accessToken
     * @param content
     * @return
     */
    public static String sendPostRequest(String accessToken, String content) {
        // 创建一个HttpHeaders对象，并设置内容类型为application/json
        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);

        // 将accessToken添加到请求头中
//        headers.set("Authorization", "Bearer " + accessToken);

        // 将请求体内容封装为HttpEntity
        org.springframework.http.HttpEntity<String> requestEntity = new org.springframework.http.HttpEntity<>(content, headers);
        RestTemplate restTemplate = new RestTemplate();
        // 发送POST请求并接收响应
        org.springframework.http.ResponseEntity<String> responseEntity = restTemplate.exchange(
                CHATGPT_API_URL + "?access_token=" + accessToken,
                org.springframework.http.HttpMethod.POST,
                requestEntity,
                String.class
        );
        String body = responseEntity.getBody();
        System.out.println(body);
        // 获取响应体内容
        return responseEntity.getBody().toString();

    }

    /**
     * 获取接口访问凭证
     *
     * @param appid     凭证
     * @param appsecret 密钥
     * @return
     */
    public static Token getToken(String appid, String appsecret) throws Exception {
        Token token = null;
        String requestUrl = ConstantUtil.token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        // 发起GET请求获取凭证
        JSONObject jsonObject = (JSONObject) HttpUtils.httpsRequest(requestUrl);

        if (null != jsonObject) {
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
//                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getString("errmsg"));
                throw new Exception(e.toString());
            }
        }
        return token;
    }


}
